package com.xoa.service.cms.core;

import com.xoa.service.cms.CmsChannelService;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;
/**
 * @author 程叶同
 * @date 2018/8/13 14:42
 * @desc  模板栏目RootPath标签解析 获取链接地址
 */
public class CmsRootPathDirective implements TemplateDirectiveModel {

	@Override
	public void execute(Environment env, Map params, TemplateModel[] loopVars,
                        TemplateDirectiveBody body) throws TemplateException, IOException {
		// TODO Auto-generated method stub

		String src = FileUtils.getString(params.get("src"));
		int siteId = FileUtils.getInteger(env.getCustomAttribute("SITE_ID"),0);
		int curChannelId = FileUtils.getInteger(env.getCustomAttribute("CHANNEL_ID"), 0);
		CmsChannelService channelService = (CmsChannelService) env.getCustomAttribute("channelService");
		boolean preview = (Boolean) env.getCustomAttribute("preview");
		Writer writer = env.getOut();
//获取数当前登陆库
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String dateSouse ="xoa"+(String)request.getSession().getAttribute("loginDateSouse");
		if(preview){
			writer.write("/cmstpls/"+dateSouse+"/"+siteId+"/"+src);
		}else{
			String channelPath="";
			if(curChannelId>0){
				 channelPath = channelService.getChannelRootPath(curChannelId);
				 writer.write(channelPath+"/"+src);
			}else{
				writer.write(src);
			}
		}
	}

}
